package org.lex.swing.graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

public class DefaultProgressModel extends AbstractProgressModel implements ProgressModel {
	// ��list�������/ɾ�����ʱ��ȷ��ά��list�������
	private final Vector<Range> list = new Vector<Range>();

	@Override
	public Range getRange(int index) {
		return list.get(index);
	}

	@Override
	public int getRangeCount() {
		return list.size();
	}

	@Override
	public void addRange(Range r) {
		/**
		 * <pre>
		 * 	    start       end
		 * -------+----------+---------
		 *   (1)      (2)        (3)
		 * </pre>
		 */
		if (r.start > this.getMaximum())
			return;
		list.add(r);
		normalize();
		this.fireRangesAdded(r);
	}

	void normalize() {
		if (list.size() < 2)
			return;
		Collections.sort(list, Range.START_COMPARATOR);
		Range last = list.get(0);
		ArrayList<Range> remove = new ArrayList<Range>();
		for (int i = 1; i < list.size(); i++) {
			Range cur = list.get(i);
			if (last.contains(cur.start())) {
				last.end = Math.max(last.end, cur.end);
				if (last.end > this.getMaximum())
					last.end = this.getMaximum();
				remove.add(cur);
			} else {
				last = cur;
			}
		}
		for (Range r : remove)
			list.remove(r);
	}

	boolean contains(long start, long end, long x) {
		return x >= start && x <= end;
	}

	@Override
	public void removeRange(Range r) {
		// FIXME
	}
}
